package srzy.driver

import srzy.data.PublicData
import srzy.common.Logging
import srzy.socket.DCCMsgActor
import srzy.module.CaseDeal
import srzy.common.Common
import srzy.diameter._
import srzy.socket._
import srzy.dao.DBUtil
import java.io.File

object Start extends Logging {

  def deal = {
    PublicData
    try {
      logger.debug("start DCCMsgActor")
      DCCMsgActor().start
      logger.debug("start DCCMsgActor over")
      logger.debug("start RBMsgTransitActor")
      RBMsgTransitActor
      logger.debug("start RBMsgTransitActor over")
      logger.debug("start DBUtil")
      DBUtil
      logger.debug("start DBUtil over")

      logger.debug("all connection success")
      CaseDeal.dealAllCase
      //      val res = (DCCMsgActor() !! 'exit).apply
      //      logger.debug("DCCMsgActor stop state " + res)
      //      Thread.sleep(1000L)
      logger.debug("aplication run over")
      sys.exit

    } catch {
      case ex: Exception => {
        logger.error(ex.getMessage(), ex)
        sys.exit
      }
    }
  }

  def main(args: Array[String]): Unit = {
    deal
  }

  def deal13 = {

    //    val l = srzy.common.packunpack.unpackInt("00019000".hexToBytes, 0)
    //    println(l)
    //
    //    "00019000".hexToBytes.toHexString
    //    //    println('a'.toInt)
    //    //    println('0'.toInt)
    import srzy.diameter.DataFormat._

    val header = "010000b08000010100000000000007d1000007d1".hexToBytes
    val dccHeaderInfo = dccHeaderFieldsInfo.map(x => {
      val e1 = x._1
      val e2 = x._2
      (e1, srzy.common.packunpack.unpackLong(header, e2._1, e2._2))
    })
    println("dccHeaderFieldsInfo:" + dccHeaderFieldsInfo)
    println("dccHeaderInfo:" + dccHeaderInfo)
  }

  def deal12 = {

  }

  def deal11 = {
    if (System.getenv("flag") == "1") {
      dealDccserver
    } else {
      deal10
    }
  }

  def deal10 = {

    DCCServer
    DCCMsgDealer.start

    //    val l = new File("case").listFiles().filter(_.isDirectory()).toList.flatMap(_.listFiles().toList)
    val l = new File("case").listFiles().filter(x => x.isDirectory()).flatMap(x => x.listFiles())
    def getCmd(a: String) = "/sm/hp_sm/acgzone/seagull/bin/seagull -conf /sm/hp_sm/acgzone/seagull/config/conf.client.xml -dico /sm/hp_sm/acgzone/seagull/config/uni_ocs_ocp_dict.xml -scen " +
      a +
      " -log /sm/hp_sm/acgzone/seagull/log/dcclog -llevel A -notimelog -bg"
    l.foreach(x => {

      val fileName = x.getName()
      logger.debug("fileName:" + fileName)
      val path = x.getAbsolutePath()
      val txt = srzy.common.Common.readFromFile(x).filter(x => x.indexOf("HbH-id") == -1 && x.indexOf("EtE-id") == -1)
      srzy.common.Common.writeToFile(path, txt.mkString("\n"))

      val se = new srzy.common.ShellExecute {
        val shell = getCmd(path)
      }
      if (se.execute != 0) {
        sys.exit
      }
      var str = (DCCMsgDealer !! 'getRece).apply.toString

      //      val filePath = "newcase/" + fileName
      //      logger.debug("filePath:" + filePath)

      val caseName = x.getName().replace(".xml", "")
      logger.debug("caseName:" + caseName)

      val r = """<avp name="Session-Id" value="[\x00-\x7F]+?"></avp>""".r
      str = r.replaceAllIn(str, """<avp name="Session-Id" value="sm.auto.test;"""
        + caseName + """"></avp>""")

      sys.env.get("OriginHost") match {
        case Some(originHost) => {
          val r1 = """<avp name="Origin-Host" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Origin-Host" value=""""
            + originHost + """"></avp>""")
        }
        case None => {
          val r1 = """<avp name="Origin-Host" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Origin-Host" value=""""
            + "sm-all-test" + """"></avp>""")
        }
      }

      sys.env.get("OriginRealm") match {
        case Some(originRealm) => {
          val r1 = """<avp name="Origin-Realm" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Origin-Realm" value=""""
            + originRealm + """"></avp>""")
        }
        case None => {
          val r1 = """<avp name="Origin-Realm" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Origin-Realm" value=""""
            + "chinaunicom.com" + """"></avp>""")
        }
      }

      sys.env.get("HostIPAddress") match {
        case Some(hostIPAddress) => {
          val r1 = """<avp name="Host-IP-Address" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Host-IP-Address" value=""""
            + hostIPAddress + """"></avp>""")
        }
        case None => {
          val r1 = """<avp name="Host-IP-Address" value="[\x00-\x7F]+?"></avp>""".r
          str = r1.replaceAllIn(str, """<avp name="Host-IP-Address" value=""""
            + "0x000100000000" + """"></avp>""")
        }
      }

      srzy.common.Common.writeToFile(path, str)

      logger.debug("fileName:" + fileName + " deal over")
    })
  }

  def dealDccserver = {
    DCCServer
    DCCMsgDealer.start
    while (true) {
      logger.debug((DCCMsgDealer !! 'getRece).apply.toString)
    }
  }

  def deal7 = {
    import srzy.rb.RBMsg
    val stdMsg = "[100=90][101=20140828142006][000=hqq_cxvas_20141021423][001=3464148826556729308][R85=1][R01=13200007777][R02=13200007777][R03=13253370160][R40=000,R401=481,R402=10,R405=2,R406=8888,R407=100,R408=ClientIP,R409=chb_cxvas_2014092316290,R410=0][R50=000,R503=6000025501,R504=0556,R506=3,R507=010,R509=3,R5012=0556][R60=000,R601=0,R602=4,R603=0,R604=20141229130215,R605=0][B03=000,B036=2,B037=100,B038=0,B0391=2;B03=000,B036=6,B037=1,B038=0,B0391=2][B06=1][B07=1][B08=1][B20=1][B21=1][B15=1]"
    val realMsg = "[100=90][101=20140828142006][000=hqq_cxvas_20141021423][001=3462830512115025884][R85=1][R01=13200007777][R02=13200007777][R03=13253370160][R40=000,R401=481,R402=10,R405=2,R406=8888,R407=100,R408=ClientIP,R409=chb_cxvas_2014092316290,R410=0][R50=000,R503=6000025501,R504=0556,R506=3,R507=010,R509=3,R5012=0556][R60=000,R601=0,R602=4,R603=0,R604=20141229130934,R605=0][B03=000,B036=6,B037=1,B038=0,B0391=2;B03=000,B036=2,B037=100,B038=0,B0391=2][B06=1][B07=1][B08=1][B20=1][B21=1][B15=1]"

    logger.debug(RBMsg.compare2(stdMsg, realMsg))

  }

  def deal8 = {
    import srzy.rb.RBMsg
    val stdMsg = "[100=90][101=20140828142006][000=hqq_cxvas_20141021423][001=3464148826556729308][R85=1][R01=13200007777][R02=13200007777][R03=13253370160][R40=000,R401=481,R402=10,R405=2,R406=8888,R407=100,R408=ClientIP,R409=chb_cxvas_2014092316290,R410=0][R50=000,R503=6000025501,R504=0556,R506=3,R507=010,R509=3,R5012=0556][R60=000,R601=0,R602=4,R603=0,R604=20141229130215,R605=0][B03=000,B036=6,B037=1,B038=0,B0391=2;B03=000,B036=2,B037=100,B038=0,B0391=2][B06=1][B07=1][B08=1][B20=1][B21=1][B15=1]"
    val realMsg = "[100=90][101=20140828142006][000=hqq_cxvas_20141021423][001=3462830512115025884][R85=1][R01=13200007777][R02=13200007777][R03=13253370160][R40=000,R401=481,R402=10,R405=2,R406=8888,R407=100,R408=ClientIP,R409=chb_cxvas_2014092316290,R410=0][R50=000,R503=6000025501,R504=0556,R506=3,R507=010,R509=3,R5012=0556][R60=000,R601=0,R602=4,R603=0,R604=20141229130934,R605=0][B03=000,B036=6,B037=1,B038=0,B0391=2;B03=000,B036=2,B037=100,B038=0,B0391=2][B06=1][B07=1][B08=1][B20=1][B21=1][B15=1]"

    println(stdMsg.substring(stdMsg.indexOf("[") + 1,
      stdMsg.lastIndexOf("]")).split("\\]\\[").toList.mkString("\n"))
  }

  def deal9 = {

    def leftPad(str: String, i: Int, pad: Char = '0') = (List.fill(i)(pad).mkString("") + str).substring(str.length())

    //    val l = new java.io.File("case/wlan")
    //    l.listFiles().toList.foreach(x => {
    //      val n = x.getName()
    //      val regex = """([0-9]+).([0-9]+).([0-9]+)_([a-z]+).xml""".r
    //      val regex(d1, d2, d3, t) = n
    //      val newName = t + "_" + d1 + "." + d2 + "." + leftPad(d3, 2) + ".xml"
    //      logger.debug(newName)
    //      x.renameTo(new File("case/wlan/" + newName))
    //    })

    new java.io.File("case").listFiles().foreach(
      x => x.renameTo(new File("case/" + x.getName().replace("in", "voice"))))

    val l = new java.io.File("case").listFiles()
    //.toList.filter(_.isDirectory()).flatMap(_.listFiles().toList)

    l.foreach(x => {
      val name = x.getName()
      val caseName = name.replace(".xml", "")
      //      val regex = """([a-z]+)_([0-9.]+).xml""".r
      //      val regex(t, id) = name

      //      val caseName = t + ";" + id
      val fl = Common.readFromFile(x)
      val fl2 = fl.map(y => {
        val r = """<avp[ ]+name="Session-Id"""".r
        r.findFirstIn(y) match {
          case Some(v) =>
            """        <avp name="Session-Id" value="sm.auto.test;""" +
              caseName + """"></avp>"""
          case None => y
        }
      })
      Common.writeToFile(x, fl2.mkString("\n"))
      logger.debug("caseName:" + caseName)

      //      println("1\t" + name + "\t" + t)
    })
  }
}

